import { getRequest } from "./api";

export const initMenu = (router, store)=>{
  // 判断store.routes是否有值
  if(store.state.routes.length > 0){
    return;
  }
  // 发送请求并处理
  getRequest('/system/cfg/menu').then(data=>{
    if(data){
      // 格式化路由
      let fmtRoutes = formatRoutes(data.obj);
      // 添加路由
      router.addRoutes(fmtRoutes);
      // 将数据存入vuex
      store.commit('initRoutes', fmtRoutes);
      // 连接Socket
      store.dispatch('connect')
    }
  })
}

// 格式化路由的函数
export const formatRoutes = (routes)=>{
  let fmtRoutes = [];
  routes.forEach(router=>{
    if(router.name != '所有'){
      let {
        path,
        component,
        name,
        iconCls,
        children
      } = router;
      if(children && children instanceof Array){
        children = formatRoutes(children)
      }
      // 格式化好后的对象
      let fmRouter = {
        path: path,
        name: name,
        iconCls: iconCls,
        children: children,
        // 路由组件懒加载ES5
        component(resolve){
          if(component.startsWith('Home')){
            require(['../views/'+component+'.vue'], resolve)
          }else if(component.startsWith('Emp')){
            require(['../views/emp/'+component+'.vue'], resolve)
          }else if(component.startsWith('Per')){
            require(['../views/per/'+component+'.vue'], resolve)
          }else if(component.startsWith('Sal')){
            require(['../views/sal/'+component+'.vue'], resolve)
          }else if(component.startsWith('Sta')){
            require(['../views/sta/'+component+'.vue'], resolve)
          }else if(component.startsWith('Sys')){
            require(['../views/sys/'+component+'.vue'], resolve)
          }
        }
        // ES6
        // component: () => import ('../views/'+component+'.vue')
      }
      // 存入数组并返回
      fmtRoutes.push(fmRouter)
    }
  });
  // console.log(fmtRoutes);
  return fmtRoutes;
}